#include "zrpc/base/logger.h"
#include "zrpc/http/http_server.h"

void OnMessageCallback(const std::shared_ptr<zrpc::TcpConnection>&,
  const zrpc::HttpRequest& request,
  zrpc::HttpResponse* response) {
  for (const auto& header : request.GetHeaders()) {
    LOG_INFO << header.first << " " << header.second;
  }

  LOG_INFO << "path:" << request.GetPath();
  LOG_INFO << "query:" << request.GetQuery();
  LOG_INFO << "body:" <<  request.GetBody();
	
  if (request.GetMethod() == zrpc::HttpRequest::kGet) {
    if (request.GetPath() == "/") {
      response->SetStatusCode(zrpc::HttpResponse::k200k);
      response->SetStatusMessage("OK");
      response->SetContentType("text/html");
      response->AddHeader("server", "http");
      response->SetBody(
        "<html><head><title>This is title</title></head>"
        "<body><h1>Hello</h1>Now is " +
        zrpc::TimeStamp::Now().ToFormattedString() + "</body></html>");
    }
    else if (request.GetPath() == "/favicon.ico") {
      response->SetStatusCode(zrpc::HttpResponse::k200k);
      response->SetStatusMessage("OK");
      response->SetContentType("image/png");
      response->SetBody("test_image");
    }
    else if (request.GetPath() == "/hello") {
      response->SetStatusCode(zrpc::HttpResponse::k200k);
      response->SetStatusMessage("OK");
      response->SetContentType("text/plain");
      response->AddHeader("server", "http");
      response->SetBody("hello, world!\n");
    }
    else if (request.GetPath() == "/test.txt") {
      std::string filename = "attachment;filename=test.txt";
      response->SetStatusCode(zrpc::HttpResponse::k200k);
      response->SetStatusMessage("OK");
      response->SetContentType("text/plain");
      response->AddHeader("Content-Disposition", filename);
      response->SetBody("test!\n");
    }
    else {
      response->SetStatusCode(zrpc::HttpResponse::k404NotFound);
      response->SetStatusMessage("Not Found");
      response->SetCloseConnection(true);
    }
  }
  else if (request.GetMethod() == zrpc::HttpRequest::kPost) {
    response->SetStatusCode(zrpc::HttpResponse::k200k);
    response->SetStatusMessage("OK");
  }
}

int main() {
  zrpc::HttpServer server("127.0.0.1", 6379);
  server.SetMessageCallback(OnMessageCallback);
  server.Start();
  server.Run();
  return 0;
}
